package com.test.request;

import java.io.IOException;

import com.alibaba.fastjson.JSONObject;
import com.test.publicmethod.PublicHelp;
import okhttp3.*;

import java.io.File;

public class PostRequest{

    OkHttpClient okHttpClient = new OkHttpClient();
    public static final MediaType type = MediaType
            .parse("application/x-www-form-urlencoded;charset=utf-8;application/json");

    //普通的POST请求BODY
    public  RequestBody SetGeneralPostBody(JSONObject paramJO){

        //强制类型转换，把JSONObject类型转换成String
        String str=paramJO.toString();
        //设置请求的参数格式
        MediaType JasonData=MediaType.get("application/json; charset=utf-8");
        //设置请求body
        RequestBody reqBody=RequestBody.create(type,str);

        return reqBody;
    }

    //表单POST请求BODY
    public FormBody SetFormPostBody(JSONObject paramJO){
        FormBody.Builder formBuilder = new FormBody.Builder();
        //遍历添加请求参数
        if (null != paramJO) {
            for (String key : paramJO.keySet()) {
                formBuilder.add(key, paramJO.getString(key));
            }
        }

        FormBody formBody = formBuilder.build();
        return formBody;
    }
    //文件上传提交BODY
    public RequestBody  SetFileUploadBody(String FileName,String Title,String PathName){
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        RequestBody FileBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title", Title)
                .addFormDataPart("image", FileName,RequestBody.create(MEDIA_TYPE_PNG,new File(PathName)))
                .build();
        return FileBody;
    }

    //发送POST请求
    public void SendPostReq(String req,RequestBody body,Headers headers){
        //请求组合创建
        Request request=new Request.Builder()
                .url(req)
                .post(body)
                .headers(headers)
                .build();
        //发起请求
        Response res=null;
        try {
            res=okHttpClient.newCall(request).execute();
            if(!res.isSuccessful()) {
                throw new IOException("服务器异常"+res);
            }
            System.out.println(res.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String post(String url, String param,int reqtype) {
        JSONObject paramHeaderJO = JSONObject.parseObject(param);
        //取出post请求的入参值
        JSONObject paramJO = (JSONObject) paramHeaderJO.get("param");
        //取出posrt请求的header的入参值
        JSONObject headerJO = (JSONObject) paramHeaderJO.get("headers");
//        System.out.println(paramJO);
//        System.out.println(headerJO);
        //设置请求body
        okhttp3.Request.Builder requestBuilder;

        if(reqtype==1){
            RequestBody reqbody=SetGeneralPostBody(paramJO);
            requestBuilder = new Request.Builder().url(url).post(reqbody);
        }else if(reqtype==2){
            FormBody reqbody=SetFormPostBody(paramJO);
            requestBuilder = new Request.Builder().url(url).post(reqbody);
        }else if(reqtype==3){
            RequestBody reqbody=SetFileUploadBody("imagephoto","autotest","D:/1.png");
            requestBuilder = new Request.Builder().url(url).post(reqbody);
        }else{
            System.out.println("请求类型有误，请检查后重试");
            return "0";
        }


        //遍历添加header参数
        if (null != headerJO) {
            for (String key : headerJO.keySet()) {
                requestBuilder.addHeader(key, headerJO.getString(key));
            }
        }
        Request request = requestBuilder.build();

        Response response;
        Call call = okHttpClient.newCall(request);
        try {
            response = call.execute();
            response.headers();
            System.out.println(response.headers());
            return response.body().string();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.err.println();
            return "请求错误aaa";
        }

    }

}
